<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

	class Places extends CI_Controller {
		function __construct(){
			parent::__construct();
			$this->load->model('Places_model');			
		}
		function add(){
			$this->_is_logged_in();
			$this->load->library('form_validation');
			$this->form_validation->set_error_delimiters('<div class="error"><div></div>', '</div>');
			$config = array(
						array( 'field'   => 'nombre', 
							   'label'   => 'Nombre', 
							   'rules'   => 'trim|required'
							  ),
						array( 'field'   => 'descripcion', 
							   'label'   => 'Descripcion', 
							   'rules'   => 'trim|required'
							  ),
						array( 'field'   => 'latitud', 
							   'label'   => 'Latitud', 
							   'rules'   => 'trim|numeric'
							  ),
						array( 'field'   => 'longitud', 
							   'label'   => 'Longitud', 
							   'rules'   => 'trim|numeric|callback__check_coor['.$this->input->post('latitud').']'
							  ),
						array( 'field'   => 'categ', 
							   'label'   => 'categoria', 
							   'rules'   => 'trim|required'
							  ),
						array( 'field'   => 'ciudad', 
							   'label'   => 'ciudad en la que se encuentra', 
							   'rules'   => 'callback__city_check'
							  ),						
						);
						
			
			$this->form_validation->set_rules($config);
			
			if ($this->form_validation->run() == FALSE){
				$menu=$this->_menu();
				$categorias=$this->Places_model->categorias();
				$data=array(
							'main_content' 	=> 'places/add.php',
							'categorias'	=> $categorias,
							'menu'			=> $menu,
							'current'		=> 3
							);
				$this->load->view('includes/template', $data);
			}
			else
			{
				$id_user = $this->session->userdata['user_id'];				
				$nombre = $this->input->post('nombre');
				$categoria = $this->input->post('categ');
				$descripcion = $this->input->post('descripcion');
				$lat = $this->input->post('latitud');
				$long = $this->input->post('longitud');
				if($categoria=='0')
					$ciudad = $nombre;
				else
					$ciudad = $this->input->post('ciudad');
				//$id_google = $this->_google_add_place($nombre,$lat,$long);
				//$result = $this->Places_model->add($id_user,$id_google->id,$id_google->reference,$nombre,$categoria,$ciudad,$descripcion,$lat,$long);
				$result = $this->Places_model->add($id_user,NULL,NULL,$nombre,$categoria,$ciudad,$descripcion,$lat,$long);
				redirect('places/details/'.$result);
			}
		}
		
		function myPlaces(){
			$this->_is_logged_in();			
			$result=$this->Places_model->myPlaces($this->session->userdata['user_id']);
			$menu=$this->_menu();
			$data=array(
					'main_content'  =>'places/mapa.php',
					'js'			=>'myPlaces.js',
					'result'		=>$result,
					'menu'			=>$menu,
			  		'current'		=>2
			);
			$this->load->view('includes/template', $data);
		}
		function myPlacesAjax(){
			if(!isset($this->session->userdata['is_logged_in']) || 
				$this->session->userdata['is_logged_in'] != true){
				echo 'Debes iniciar sesion';
				return;
			}
			
			$id_user=$this->session->userdata['user_id'];
			$result = $this->Places_model->myPlaces($id_user);
			$data=array(	
					'places'		=>$result
			);
			$this->load->view('places/myPlaces', $data);
		}
		function details($id_lugar){			
			$this->session->set_flashdata('redirect', $this->uri->uri_string());
			$result = $this->Places_model->details($id_lugar);
			if(empty($result))
				redirect('mapa');
			$this->load->model('Comments_model');
			$comentarios=$this->Comments_model->get($id_lugar);
			
			$puntuacion = $this->Places_model->calificacion($id_lugar);
			if(isset($this->session->userdata['is_logged_in'])){
				$id_usuario=$this->session->userdata['user_id'];
				$puntuacionUsuario = $this->Places_model->calificacionUsuario($id_lugar,$id_usuario);
			}
			$this->session->set_userdata(array('id_site'=>$id_lugar));
			$notas=$this->_notas($id_lugar);
			
			$menu=$this->_menu();
			$menu['notas']=$notas;
			
			$data=array(
					'main_content'	=>'places/details.php',
					'detalles'		=>$result,
					'comentarios'	=>$comentarios,
					'id_lugar'		=>$id_lugar,
					'js'			=>'detalles.js',
					'puntuacion'	=>$puntuacion,
					'menu'			=>$menu,
					'current'		=>-1
			);
			if(isset($this->session->userdata['is_logged_in'])){
				$data['puntuacionUsuario'] = $puntuacionUsuario;
			}
			$this->load->view('includes/template', $data);
		}
		
		function allPlaces($page=0){
			$this->load->library('table');
			$menu=$this->_menu();
			$data=array(
					'main_content'	=>'places/allPlaces.php',
					'menu'			=>$menu,
					'current'		=>4,
					'js'			=>'jquery.dataTables.min.js'
			);
			$this->load->view('includes/template', $data);
		}	
		function allPlacesAjax(){
			$cant=$this->input->post('iDisplayLength');
			$start=$this->input->post('iDisplayStart');
			$iSortCol=$this->input->post('iSortCol_0');
			$sSortDir=$this->input->post('sSortDir_0');
			$result = array(
						'places'=>$this->Places_model->allPlaces($start,$cant,$iSortCol,$sSortDir),
						'total'			=>$this->Places_model->cantPlaces()
			);
			$this->load->view('places/allPlacesAjax', $result);
		}
		function search(){
			$result = $this->Places_model->search($this->input->get('term'));
			$data=array(
					'result'		=>$result
			);
			$this->load->view('places/search', $data);
		}
		
		function calificar(){
			if(isset($this->session->userdata['is_logged_in'])&&$this->session->userdata['is_logged_in']==true){
				$calific=$this->input->post('rating');
				$id_user=$this->session->userdata['user_id'];
				$id_site=$this->session->userdata['id_site'];
				if(isset($id_site) && isset($id_user) && isset($calific))
					if($calific>=0 && $calific<=5){
						$this->Places_model->calificar($id_site,$id_user,$calific);
						$data=array(
								'calificacion'		=> $this->Places_model->calificacion($id_site),
								'status'			=> 'ok'
						);
						$this->load->view('places/calificar', $data);
						return;
					}
			}
			$data=array(
					'calificacion'		=> null,
					'status'			=> 'error'
			);
			$this->load->view('places/calificar', $data);
		}
		
		function ruta($id){
			$result = $this->Places_model->details($id);
			$data['place']=$result;		
			$this->load->view('places/ruta', $data);
		}
		
		function editDesc(){
			$idPlace=$this->input->post('id');
			if(isset($this->session->userdata['is_logged_in'])&&$this->session->userdata['is_logged_in']==true){
				$userID=$this->session->userdata['user_id'];
				$descripcion=$this->input->post('descripcion');
				$id=$this->Places_model->getUser($idPlace);
				
				if($userID==$id){
					$aux = trim($descripcion);
					if(strlen($aux)>1)
						$this->Places_model->editDesc($idPlace,$descripcion);
					else
						$this->session->set_flashdata('error', 'Ingrese un comentario');
				}
				else
					$this->session->set_flashdata('error', 'No puede editar este lugar');
			}else{
				$this->session->set_flashdata('error', 'Debe iniciar sesion para editar');
			}
			redirect('places/details/'.$idPlace);
		}
		
		function _is_logged_in(){
			$is_logged_in = $this->session->userdata['is_logged_in'];
			if(!isset($is_logged_in) || $is_logged_in != true){
				$data=array('page'=>'places/'.$this->uri->segment(2));
				$this->session->set_userdata($data);
				redirect('users/login');		
			}
		}
		
		function _google_add_place($nombre,$lat,$long){
			require_once('googlePlaces.php');
			
			$gplaces = New GooglePlaces;
			$gplaces->SetName($nombre);
			$gplaces->SetLocation($lat.','.$long);
			$gplaces->SetAccuracy(100);
			$gplaces->SetTypes("park");
			
			$results = $gplaces->Add();
			return $results;
		}
		
		function _city_check($city){
			$categ =$this->input->post('categ');
			$nombre=$this->input->post('nombre');
			if(!isset($categ) || !isset($nombre)){
				$this->form_validation->set_message('_city_check','');
				return false;
				
			}
			if($categ=='0')
				if(!isset($city) || $nombre==$city){
					return true;
				}
				else{
					$this->form_validation->set_message('_city_check','los campos nombre y ciudad no coinciden');
					return false;
				}					
			else
				if(empty($city)){
					$this->form_validation->set_message('_city_check','Ingrese la ciudad en la que se encuentra el lugar');
					return false;
				}else{
					$this->form_validation->set_message('_city_check','Ingrese ');
					return true;
				}
		}

		function _check_coor($lng,$lat){
			if(empty($lat) || empty($lng)){
				$this->form_validation->set_message('_check_coor','Seleccione la ubicacion en el mapa');
				return false;
			}
			return true;
		}
		function _menu(){
			$mejores = $this->_mejorPuntuacion();
			$ultimos = $this->_ultimos();
			return array(
					'mejores' =>$mejores,
					'ultimos' =>$ultimos
			);
		}
		function _mejorPuntuacion(){
			$this->load->model('Calificacion_model');	
			return $this->Calificacion_model->mejorPuntuacion();
		}
		function _ultimos(){
			return $this->Places_model->ultimosSitios();
		}
		function _notas($id_lugar){
			$this->load->model('Nota_model');	
			return $this->Nota_model->getNotes($id_lugar);
		}
	}
	
?>